﻿using System;
using System.IO;
using System.Linq;
using System.Threading;
using EnvDTE;
using SolutionFactory.Services;
using SolutionFactory.UI;

namespace SolutionFactory.Exporter
{
    public class ExportGenerator
    {
        private readonly TemplateInputController _controller;
        private readonly DTE _dte;
        private readonly IFileSystem _fileSystem;
        private readonly IMessageBox _messageBox;
        private readonly SolutionExporter _solutionExporter;
        private TemplateInput model;

        public ExportGenerator(DTE dte, IFileSystem fileSystem, IMessageBox messageBox,
                               TemplateInputController controller, SolutionExporter solutionExporter)
        {
            _dte = dte;
            _fileSystem = fileSystem;
            _messageBox = messageBox;
            _controller = controller;
            _solutionExporter = solutionExporter;
        }

        public void Generate()
        {
            try
            {
                if (_dte.Solution.IsOpen)
                {
                    model = _controller.Run(GetSolutionRootCommandFiles());
                    if (model != null)
                    {
                        ThreadPool.QueueUserWorkItem(ExportSolution, this);
                    }
                }
            }
            catch (Exception ex)
            {
                _messageBox.ShowError(ex.ToString());
            }
        }

        private string[] GetSolutionRootCommandFiles()
        {
            string solutionDir = _fileSystem.GetDirectoryName(_dte.Solution.FileName);
            string solutionDirRoot = _fileSystem.GetFullPath(Path.Combine(solutionDir, "..\\"));
            return _fileSystem.GetFilesInDirectory(solutionDirRoot, "*.*").Where(s => s.ToLower().EndsWith(".bat")
                                                                                      || s.ToLower().EndsWith(".cmd"))
                .Select(s => _fileSystem.GetFileNameWithExtension(s)).ToArray();
        }

        private void ExportSolution(object state)
        {
            var generator = (ExportGenerator) state;
            TemplateInput model = generator.model;
            _solutionExporter.Export(_dte.Solution, model);
        }
    }
}